<template>
  <div class="mod-user">
    <div class="mod-user">
      <el-form :model="query" :inline="true">
        <el-form-item>
          <el-select
            @change="changeSchoolTypeForQuery"
            v-model="query.schoolType"
            filterable
            clearable
            placeholder="请选择阶段">
            <el-option
              v-for="item in schoolTypeListForQuery"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            @change="changeGradeTypeForQuery"
            v-model="query.gradeType"
            filterable
            clearable
            placeholder="请选择年级">
            <el-option
              v-for="item in gradeTypeListForQuery"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            v-if="query.gradeType"
            v-model="query.subjectId"
            filterable
            clearable
            placeholder="请选择科目">
            <el-option
              v-for="item in subjectListForQuery"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="success" v-if="hasPermission(['system:paperSetting:list'])" icon="el-icon-search" @click="searchPaperSettingList">查询</el-button>
          <el-button type="primary" v-if="hasPermission(['system:paperSetting:save'])" @click="addPaperSetting">新增组卷设置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="paperSettingList"
        :indent="30"
        border
        row-key="value"
        v-loading="loading"
        style="width: 100%;">

      <!--  <el-table-column
          prop="language_points_name"
          header-align="center"
          align="center"
          label="知识点内容">
        </el-table-column>-->


        <el-table-column
          prop="grade_type"
          header-align="center"
          align="center"
          label="所属阶段">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.school_type === 1" size="small">小学</el-tag>
            <el-tag v-else-if="scope.row.school_type === 2" size="small">初中</el-tag>
            <el-tag v-else="scope.row.school_type === 3" size="small">高中</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="grade_type"
          header-align="center"
          align="center"
          label="所属年级">
          <template slot-scope="scope">
            <el-tag size="small">{{scope.row.grade_type | getGradeName}}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="subject_name"
          header-align="center"
          align="center"
          label="所属科目">
        </el-table-column>

        <el-table-column
          prop="subject_name"
          header-align="center"
          align="center"
          label="纠错类型">
        </el-table-column>

        <el-table-column
          prop="subject_name"
          header-align="center"
          align="center"
          label="所属课程/试卷">
        </el-table-column>

        <el-table-column
          prop="paper_question_number"
          align="center"
          label="组卷试题数量">
        </el-table-column>

        <el-table-column
          prop="create_date"
          header-align="center"
          align="center"
          width="180"
          :formatter="formatterCreateDate"
          label="创建时间">
        </el-table-column>

        <el-table-column
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="hasPermission(['system:paperSetting:update'])"
              size="small"
              @click="updateSetting(scope.row)"
              type="warning">修改</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <el-dialog
        :title="!form.id ? '新增错题组卷设置' : '修改错题组卷设置'"
        :close-on-click-modal="false"
        :visible.sync="showFlag">
        <el-form :model="form" :rules="rules" ref="form" @keyup.enter.native="saveOrUpdateAiPaperSetting()" label-width="120px">
          <el-form-item label="所属阶段" placeholder="所属阶段" prop="school_type">
            <el-select
              @change="changeSchoolType"
              v-model="form.school_type"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in schoolTypeList"
                :key="item.id"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所属年级" placeholder="所属年级" prop="grade_type">
            <el-select
              @change="changeGradeType"
              v-model="form.grade_type"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in changeGradeTypeList"
                :key="item.id"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所属科目" placeholder="所属科目" prop="subject_id">
            <el-select
              v-model="form.type"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="纠错类型" placeholder="纠错类型" prop="grade_type">
            <el-select
              @change="changeType"
              v-model="form.type"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item v-if="form.type === 1" label="所属课程" placeholder="所属课程">
            <el-select
              v-model="form.course_id"
              filterable
              clearable
              placeholder="请选择所属课程">
              <el-option
                v-for="item in gradeCourseList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="组卷试题数量" prop="paper_question_number">
            <el-input v-model="form.paper_question_number" placeholder="错题自动组卷试题数量"></el-input>
            <div style="color: red" v-html="languagePointsQuestionNumberMessage"></div>
          </el-form-item>
        </el-form>

        <span slot="footer"  class="dialog-footer">
          <el-button @click="showFlag = false">取消</el-button>
          <el-button type="primary" @click="saveOrUpdateAiPaperSetting()">确定</el-button>
       </span>
      </el-dialog>
    </div>
  </div>
</template>


<script>
  import { getGradeType, getSchoolType, getSubjectList, changeSchoolTypeApi, changeGradeTypeApi } from '@/utils/education-api'
  import {isInt} from '@/utils/validate'
  let that = null
  export default {
    name: 'AiPaper',

    data () {
      let validatePaperQuestionNumber = (rule, value, callback) => {
        if (value) {
          if (!isInt(value)) {
            return callback(new Error('请输入整数'))
          }
        } else {
          return callback(new Error('请输入组卷试题数量'))
        }
        callback()
      }
      return {
        totalCount: 0,
        pageSize: 10,
        currentPage: 1,
        loading: false,
        paperSettingList: [],
        typeList: [
          {
            value: 1,
            label: '课程试题纠错'
          },

          {
            value: 2,
            label: '试卷试题纠错'
          },
        ],
        gradeTypeList: [],
        schoolTypeList: [],
        subjectList: [],
        showFlag: false,
        schoolTypeListForQuery: [],
        subjectListForQuery: [],
        gradeTypeListForQuery: [],
        query: {
          schoolType: '',
          gradeType: '',
          subjectId: ''
        },
        gradeCourseList: [],
        form: {
          languagePointsIdArray: [],
          paper_question_number: '',
          subject_id: '',
          grade_type: '',
          course_id: '',
          type: '',
          school_type: '',
          language_points_id: 0
        },
        languagePointsQuestionNumberMessage: '',
        formTreeLanguagePointsList: [],
        languagePointsQuestionNumber: 0,
        changeGradeTypeList: [],
        rules: {
          school_type: {
            required: true, message: '请选择阶段', trigger: 'blur'
          },
          grade_type: {
            required: true, message: '请选择年级', trigger: 'blur'
          },
          subject_id: {
            required: true, message: '请选择科目', trigger: 'blur'
          },
          language_points_id: {
            required: true, message: '请选择知识点', trigger: 'blur'
          },
          paper_question_number: {
            required: true, validator: validatePaperQuestionNumber, trigger: 'blur'
          }
        }
      }
    },

    watch: {
      'form.grade_type' () {
      //  this.getTreeLanguagePointsList()
      },

      'form.subject_id' () {
        this.getTreeLanguagePointsList()
      }
    },

    beforeCreate () {
      that = this
    },

    mounted () {
      let that = this
      getGradeType((data) => {
        that.gradeTypeList = data
        that.changeGradeTypeList = data
        that.gradeTypeListForQuery = data
      })

      getSchoolType((data) => {
        that.schoolTypeList = data
        that.schoolTypeListForQuery = data
      })

      getSubjectList((data) => {
        that.subjectList = data
        that.subjectListForQuery = data
      })
    //  that.getPaperSettingList()
      // that.getTreeLanguagePointsList()
    },

    methods: {

      changeType (val) {
        this.form.type = val
      },

      changeSchoolTypeForQuery (val) {
        changeSchoolTypeApi(val, data => {
          this.gradeTypeListForQuery = data
        })
      },

      changeGradeTypeForQuery (val) {
        changeGradeTypeApi(val, data => {
          this.subjectListForQuery = data
        })
      },

      sizeChangeHandle (val) {
        this.pageSize = val
        this.currentPage = 1
        this.getPaperSettingList()
      },

      currentChangeHandle (val) {
        this.currentPage = val
        this.getPaperSettingList()
      },

      searchPaperSettingList () {
        this.currentPage = 1
        this.getPaperSettingList()
      },

      // 获取选中知识点数量
      changeLanguagePoints (arrayIds) {
        let that = this
        let length = arrayIds.length
        that.form.language_points_id = arrayIds[length - 1]
        that.axios.get(that.$http.httpUrl('/system/question/getQuestionCountByLanguagePoints'), {
          params: {
            languagePointsId: that.form.language_points_id
          }
        }).then(function (response) {
          that.languagePointsQuestionNumber = response.data.data.question_number
          that.languagePointsQuestionNumberMessage = '[' + response.data.data.name + ']知识点共有试题' + that.languagePointsQuestionNumber + '道'
        })
      },

      getPaperSettingList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/ai'), {
          params: {
            offset: (that.currentPage - 1) * that.pageSize,
            limit: that.pageSize,
            schoolType: that.query.schoolType,
            gradeType: that.query.gradeType,
            subjectId: that.query.subjectId
          }
        }).then(function (response) {
          that.paperSettingList = response.data.data
          that.totalCount = response.data.total
          that.loading = false
        })
      },

      getTreeLanguagePointsList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/languagePoints'), {
          params: {
            gradeType: that.form.grade_type,
            subjectId: that.form.subject_id,
            schoolType: that.form.school_type
          }
        }).then(function (response) {
          that.formTreeLanguagePointsList = response.data
        })
      },

      formatterCreateDate (row, column) {
        if (!row.create_date) {
          return '--'
        }
        return this.moment(row.create_date).format('YYYY-MM-DD HH:mm')
      },

      changeSchoolType (val) {
        let that = this
        if (that.form.grade_type) {
          that.form.grade_type = ''
        }
        changeSchoolTypeApi(val, function (data) {
          that.changeGradeTypeList = data
        })
      },

      updateSetting (item) {
        that.axios.get(that.$http.httpUrl('/system/languagePoints/findById'), {
          params: {
            id: item.language_points_id
          }
        }).then(function (response) {
          that.showFlag = !that.showFlag
          response.data.parentIdArray.push(item.language_points_id)
          that.form = {
            id: item.id,
            languagePointsIdArray: response.data.parentIdArray,
            paper_question_number: item.paper_question_number,
            subject_id: item.subject_id,
            grade_type: item.grade_type,
            school_type: item.school_type,
            language_points_id: item.language_points_id
          }
        })
      },

      saveOrUpdateAiPaperSetting () {
        let that = this
        that.$refs['form'].validate(function (valid, rules) {
          if (valid) {
            delete (that.form.languagePointsIdArray)
            that.axios.post(that.$http.httpUrl('/system/ai'), that.form)
              .then(function (response) {
                that.showFlag = false
                if (response.data.code === 1) {
                  that.$message({
                    type: 'success',
                    message: response.data.message
                  })
                  that.clearForm(that)
                  that.languagePointsQuestionNumberMessage = ''
                  that.getPaperSettingList()
                } else {
                  that.$message({
                    type: 'error',
                    message: response.data.message
                  })
                }
              }).catch(function (error) {
                console.log(error)
              })
          } else {
            let message = ''
            for (let rule in rules) {
              message = rules[rule][0].message
              if (message) {
                break
              }
            }
            that.$message({
              type: 'error',
              message: message
            })
            return false
          }
        })
      },

      clearForm () {
        this.form = {
          languagePointsIdArray: [],
          paper_question_number: '',
          subject_id: '',
          grade_type: '',
          school_type: '',
          language_points_id: 0
        }
      },

      changeGradeType (val) {
        let that = this
        if (that.form.subject_id) {
          that.form.subject_id = ''
        }
        changeGradeTypeApi(val, function (data) {
          that.subjectList = data
        })
      },

      addPaperSetting () {
        this.showFlag = !this.showFlag
      }
    },

    filters: {
      getGradeName (gradeType) {
        for (let i in that.gradeTypeList) {
          if (that.gradeTypeList[i].code === gradeType) {
            return that.gradeTypeList[i].value
          }
        }
      }
    }
  }
</script>

<style scoped>

</style>
